package com.sdjzu.wangfuying.disableautobrightness.ui;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.sdjzu.wangfuying.disableautobrightness.R;
import com.sdjzu.wangfuying.disableautobrightness.base.BaseActivity;
import com.sdjzu.wangfuying.disableautobrightness.bean.remote.Package;
import com.sdjzu.wangfuying.disableautobrightness.util.PermissionUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.sdjzu.wangfuying.disableautobrightness.util.GameModeUtil.enableGameMode;
import static com.sdjzu.wangfuying.disableautobrightness.util.PackageUtil.getApplicationNameByPackageName;

public class SelectPackageItemActivity extends BaseActivity {
    @BindView(R.id.activity_select_package_item_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.activity_select_package_item_swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean gotoRequestUsageStatsPermissionSettingByUser = false;
    private PackageListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_package_item);

        // check permission if target is above M
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtil.isUsageStatsPermissionGranted(getContext())) {
                new AlertDialog.Builder(getContext())
                        .setTitle(R.string.activity_select_package_item_request_permission_dialog_title)
                        .setMessage(R.string.activity_select_package_item_request_permission_dialog_message)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> {
                            gotoRequestUsageStatsPermissionSettingByUser = true;
                            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        })
                        .setNegativeButton(android.R.string.cancel, (dialog, which) ->
                                Toast.makeText(getContext(), R.string.activity_select_package_item_toast_in_standard_mode, Toast.LENGTH_SHORT).show())
                        .setCancelable(false)
                        .show();
            }
        }

        adapter = new PackageListAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(adapter);
        mSwipeRefreshLayout.setOnRefreshListener(this::updatePackageList);

        updatePackageList();
    }

    private void updatePackageList() {
        new GetAllPackagesTask(getContext(), adapter, mSwipeRefreshLayout).execute();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (gotoRequestUsageStatsPermissionSettingByUser) {
                // user is guided to setting page but...
                if (!PermissionUtil.isUsageStatsPermissionGranted(getContext())) {
                    // user do not grant usage stats permission to us
                    Toast.makeText(getContext(), R.string.activity_select_package_item_toast_in_standard_mode, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    @OnClick(R.id.activity_select_package_item_fab)
    void commit(FloatingActionButton floatingActionButton) {
        List<Package> packages = adapter.getSelectedPackages();
        // add these packages to configuration set
        boolean result = true;
        for (Package pkg : packages) {
            result &= enableGameMode(getContext(), pkg.getPackageName());
        }
        if (result) {
            Toast.makeText(getContext(), R.string.activity_select_package_item_toast_add_package_ok, Toast.LENGTH_SHORT).show();
            // finish activity and notify to last activity
            setResult(200);
            finish();
        } else {
            Toast.makeText(getContext(), R.string.activity_select_package_item_toast_add_package_failed, Toast.LENGTH_SHORT).show();
        }
    }

    private static class GetAllPackagesTask extends AsyncTask<Object, Integer, Package[]> {

        private static final String TAG = "GetAllPackagesTask";
        private final WeakReference<Context> context;
        private final PackageListAdapter adapter;
        private final WeakReference<SwipeRefreshLayout> swipeRefreshLayout;

        GetAllPackagesTask(Context context, PackageListAdapter adapter, SwipeRefreshLayout swipeRefreshLayout) {
            this.context = new WeakReference<>(context);
            this.adapter = adapter;
            this.swipeRefreshLayout = new WeakReference<>(swipeRefreshLayout);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            swipeRefreshLayout.get().setRefreshing(true);
        }

        @Override
        protected Package[] doInBackground(Object... objects) {
            //获取手机内所有应用
            Intent i = new Intent(Intent.ACTION_MAIN, null);
            i.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfos = context.get().getPackageManager().queryIntentActivities(i, 0);
            List<Package> packageList = new ArrayList<>(resolveInfos.size());
            for (int j = 0; j < resolveInfos.size(); j++) {
                ResolveInfo resolveInfo = resolveInfos.get(j);
                if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                    // user's app
                    Package packag = new Package();
                    packag.setName(getApplicationNameByPackageName(context.get(), resolveInfo.activityInfo.packageName));
                    packag.setPackageName(resolveInfo.activityInfo.packageName);
                    packag.setSize(getPackageSize(packag.getPackageName()));
                    packageList.add(packag);
                }
            }
            // sort by size
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                packageList.sort((o1, o2) -> o1.getSize() > o2.getSize() ? 1 : 0);
            } else {
                Log.d(TAG, "您的安卓系统版本太低，作者并不想手动给你排个序。。。");
            }
            // generate package list result
            Package[] packages = new Package[packageList.size()];
            return packageList.toArray(packages);
        }

        private int getPackageSize(String packageName) {
            return 1000;
        }

        @Override
        protected void onPostExecute(Package[] packages) {
            super.onPostExecute(packages);
            adapter.setPackages(packages);
            adapter.notifyDataSetChanged();
            swipeRefreshLayout.get().setRefreshing(false);
        }
    }

    class PackageListAdapter extends RecyclerView.Adapter<PackageListAdapter.ViewHolder> {
        private Package[] packages = new Package[0];
        private Map<String, Boolean> selectedItemMap = new HashMap<>();

        void setPackages(Package[] packages) {
            this.packages = packages;
            // selectedItemMap.clear();
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder(
                    getLayoutInflater().inflate(
                            R.layout.activity_select_package_item_recycler_item, parent, false
                    )
            );
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.mTextName.setText(packages[position].getName());
            holder.mTextSize.setText(String.valueOf(packages[position].getSize()));
            Boolean selected = selectedItemMap.get(packages[position].getPackageName());
            if (selected != null && selected) {
                holder.mCheckedSelected.setChecked(true);
            } else {
                holder.mCheckedSelected.setChecked(false);
            }
            // setup listener
            holder.itemView.setOnClickListener(v -> {
                String packageName = packages[holder.getAdapterPosition()].getPackageName();
                boolean newVal = true;
                Boolean _selected = selectedItemMap.get(packageName);
                if (selectedItemMap.containsKey(packageName) && null != _selected) {
                    newVal = !_selected;
                }
                selectedItemMap.put(packageName, newVal);
                notifyDataSetChanged();
            });
        }

        @Override
        public int getItemCount() {
            return packages.length;
        }

        List<Package> getSelectedPackages() {
            List<Package> packageList = new LinkedList<>();
            for (String key : selectedItemMap.keySet()) {
                Boolean selected = selectedItemMap.get(key);
                if (null != selected && selected) {
                    Package pkg = new Package();
                    pkg.setPackageName(key);
                    packageList.add(pkg);
                }
            }
            return packageList;
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.activity_select_package_item_txt_package_name)
            TextView mTextName;
            @BindView(R.id.activity_select_package_item_txt_package_size)
            TextView mTextSize;
            @BindView(R.id.activity_select_package_item_checkbox_selected)
            CheckBox mCheckedSelected;

            ViewHolder(@NonNull View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }
}
